package com.blah.gwtgames.client.common.ui;

import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.KeyboardListener;

public class NumberBox extends TextBox {

	public NumberBox() {
		super();
		
		addKeyboardListener(new KeyFilter(this));
	}
	
	public NumberBox(int value) {
		this();
		
		setValue(value);
	}
	
	public int getValue()
	{
		return Integer.parseInt(getText());
	}
	
	public void setValue(int value)
	{
		setText("" + value);
	}
	
	private class KeyFilter implements KeyboardListener
	{
		private NumberBox parent;
		
		public KeyFilter(NumberBox parent)
		{
			this.parent = parent;
		}
		
		public void onKeyDown(Widget sender, char keyCode, int modifier)
		{
			if (Character.isDigit(keyCode))
				return;
			
			// isDigit doesn't seem to register the keypad
			if (keyCode >= 96 && keyCode <= 105)
				return;
			
			if (keyCode == KeyboardListener.KEY_BACKSPACE ||
				keyCode == KeyboardListener.KEY_DELETE ||
				keyCode == KeyboardListener.KEY_LEFT ||
				keyCode == KeyboardListener.KEY_RIGHT ||
				keyCode == KeyboardListener.KEY_HOME ||
				keyCode == KeyboardListener.KEY_END)
				return;
			
			parent.cancelKey();	
		}
		
		public void onKeyUp(Widget sender, char keyCode, int modifier)
		{
			
		}
		
		public void onKeyPress(Widget sender, char keyCode, int modifier)
		{
			
		}
	}

}
